﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BoneImp {
	class AttachmentTimeline : Timeline {
		int framesLength;
		float[] frames; /* time, ... */
		int slotIndex;
		string[] attachmentNames;

		public AttachmentTimeline(int frameCount) : base(frameCount) {
			this.attachmentNames = new string[frameCount];
			this.framesLength = frameCount;
			this.frames = new float[frameCount];
		}

		/* @param attachmentName May be 0. */
		void setFrame(int frameIndex, float time, string attachmentName) {
			this.frames[frameIndex] = time;
			this.attachmentNames[frameIndex] = attachmentName;
		}

		public override void apply(SkeletonBase skeleton, float time, float alpha) {
			if (time < this.frames[0]) return; /* Time is before first frame. */

			int frameIndex;
			if (time >= this.frames[this.framesLength - 1]) /* Time is after last frame. */
				frameIndex = this.framesLength - 1;
			else
				frameIndex = binarySearch(this.frames, this.framesLength, time, 1) - 1;

			string attachmentName = this.attachmentNames[frameIndex];
			skeleton.slots[this.slotIndex].setAttachment(
				attachmentName != null ? skeleton.getAttachmentForSlotIndex(this.slotIndex, attachmentName) : null);
		}

		internal override float GetDuration() {
			float longest = 0;
			for (int i = 0; i < FrameCount; i++) {
				if (frames[i * 1] > longest) {
					longest = frames[i * 1];
				}
			}
			return longest;
		}
	}
}
